//
//  SearchEngineSetting.swift
//  YoruNeko
//
//  Created by Kotori on 2021/6/21.
//

import SwiftUI

struct SearchEngineSetting: View {
    @State private var selectedEngine: String = SearchEngine.searchEngineList()[0].name
    
    let engineList = SearchEngine.searchEngineList()
    let currUserMgr = UserManager.currUserMgr
    
    var body: some View {
        List {
            ForEach(engineList) { engine in
                HStack {
                    VStack(alignment: .leading) {
                        Text(engine.name).font(.headline)
                        Text(engine.domain).font(.subheadline).foregroundColor(.gray)
                    }
                    .frame(width: 300, height: 50, alignment: .leading)
                    .background(Color.white)
                    Spacer()
                        
                    if(engine.name == selectedEngine) {
                        Image(systemName: "checkmark.circle.fill")
                            .foregroundColor(/*@START_MENU_TOKEN@*/.blue/*@END_MENU_TOKEN@*/)
                    }
                }
                .onTapGesture {
                    selectedEngine = engine.name
                    //写入到偏好设置中
                    let index = SearchEngine.searchEngineList().firstIndex(where: {$0.name == selectedEngine})
                    currUserMgr.setSearchEngineSelectIndex(index: index ?? 0)
                }
            }
            .onAppear {
                let index = currUserMgr.getSearchEngineSelectIndex()
                selectedEngine = engineList[index].name
            }
            .onDisappear {
                //多线程
                currUserMgr.commit()
            }
        }
    }
}

struct SearchEngineSetting_Previews: PreviewProvider {
    static var previews: some View {
        SearchEngineSetting()
    }
}
